package com.hyfrogx.modules.manage.service.course.impl;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hyfrogx.common.exception.MyException;
import com.hyfrogx.common.exception.ServiceException;
import com.hyfrogx.common.param.VodStatus;
import com.hyfrogx.common.qcloud.QcloudApiModuleCenter;
import com.hyfrogx.common.utils.QueryExt;
import com.hyfrogx.modules.app.entity.VodParam;
import com.hyfrogx.modules.app.utils.VodSignUtils;
import com.hyfrogx.modules.app.utils.VodUtils;
import com.hyfrogx.modules.manage.dao.course.CourseManageSectionDao;
import com.hyfrogx.modules.manage.entity.course.CourseManageEntity;
import com.hyfrogx.modules.manage.entity.course.CourseManageSectionEntity;
import com.hyfrogx.modules.manage.entity.course.CourseManageSectionWatchEntity;
import com.hyfrogx.modules.manage.entity.course.CourseOrderEntity;
import com.hyfrogx.modules.manage.service.course.CourseManageSectionService;
import com.hyfrogx.modules.manage.service.course.CourseManageSectionWatchService;
import com.hyfrogx.modules.manage.service.course.CourseManageService;
import com.hyfrogx.modules.manage.service.course.CourseOrderService;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * @author 罗春杰-技术部
 */
@Service
public class CourseManageSectionServiceImpl extends ServiceImpl<CourseManageSectionDao, CourseManageSectionEntity> implements CourseManageSectionService {
    @Autowired
    CourseManageService ManageService;

    @Autowired
    CourseManageSectionWatchService watchService;

    @Autowired
    @Lazy
    CourseOrderService orderService;

    @Override
    public Page selectSectionPage(QueryExt queryExt) {
        Map map = new HashMap();
        map.putAll(queryExt.getCondition());
        queryExt.setRecords(this.baseMapper.getAllInCourseManageSection(map,queryExt));
        return queryExt;
    }

    @Override
    public Page getAllisPutawaySection(QueryExt queryExt) {
        Map map = new HashMap();
        map.putAll(queryExt.getCondition());
        queryExt.setRecords(this.baseMapper.getAllisputawaySection(map,queryExt));
        return queryExt;
    }

    @Override
    public List<CourseManageSectionEntity> manageSectionByUid(Integer uid, Integer id) {
        List<CourseManageSectionEntity> sectionByUid = this.baseMapper.manageSectionByUid(uid, id);
        return sectionByUid;
    }

    @Override
    public Page getAllIsPutAwaySection(QueryExt queryExt) throws MyException {
        Map map = new HashMap();
        map.putAll(queryExt.getCondition());
        if(Convert.toInt(map.get("programid"))==null){
            throw new MyException("课程id不能为空");
        }
        CourseManageEntity manage = ManageService.getById(Convert.toInt(map.get("programid")));
        List<CourseManageSectionEntity> sectionEntities = this.baseMapper.getAllisputawaySection(map, queryExt);
        if (map.get("uid") != null) {
            for (CourseManageSectionEntity Section : sectionEntities) {
                Section.setIsFree(Section.getPriceType());
                if(Section.getImg()==null){
                    Section.setImg(manage.getImg());
                }
                Section.setCourseAuthor(manage.getAuthor());
                // 记录用户的观看时间比例
                CourseManageSectionWatchEntity watchEntity = watchService.getOne(new QueryWrapper<CourseManageSectionWatchEntity>()
                        .eq("uid", map.get("uid") ).eq("cid", Section.getId()));
                if (watchEntity != null) {
                    Section.setScale(watchEntity.getWatch());
                }
                // 查看课程是否被购买，被购买则显示章节免费
                int rows = orderService.count(new QueryWrapper<CourseOrderEntity>()
                        .eq("uid",map.get("uid") ).eq("cid",Convert.toInt(map.get("programid"))).eq("status",1));
                if (rows > 0) {
                    Section.setIsFree(2);
                }
            }
        }
        queryExt.setRecords(sectionEntities);

        return queryExt;
    }

    @Override
    public CourseManageSectionEntity getSectionBySort(Integer type, Integer sort, Integer programid) {
        if(type==1){
            CourseManageSectionEntity section = this.baseMapper.getupSection(sort,programid);
            return section;
        }else{
            CourseManageSectionEntity section = this.baseMapper.getDownSection(sort,programid);
            return section;
        }

    }

    @Override
    public String getSign(Integer isTranscode, Integer isScreenshot) throws ServiceException {
        String sign = VodSignUtils.getSign(isTranscode, isScreenshot);
        return sign;
    }

    @SuppressWarnings("unused")
    @Override
    public Object getInfoByFileId(VodParam vodParam) throws Exception {
        QcloudApiModuleCenter module = VodUtils.getConfig();
        TreeMap<String, Object> params = VodUtils.getParam();
        // 传入list,开始for循环,参数格式为: fileIds.n n为集合长度下标
        params.put("fileId", vodParam.getFileId());
        params.put("infoFilter.0", "basicInfo");
        String result = null;
        // call 方法正式向指定的接口名发送请求，并把请求参数params传入，返回即时接口的请求结果
        result = module.call("GetVideoInfo", params);
        JSONObject object = new JSONObject(result);
        Integer time = object.getJSONObject("basicInfo").getInt("duration");
        if(time != 0){
            return object.toString();
        }else{
            return "获取时长失败,请重新上传资源";
        }
    }

    /**
     * 获取当前视频的转码后的信息 通过id
     */
//    @Override
//    public void GetVideoInfo(String fileId, Integer duration) throws Exception {
//        /* 腾讯云id为字符串 */
//        RadioAlbumProgram program = radioAlbumProgramMapper.findByFiledId(fileId);
//        RadioAlbumProgram program2 = new RadioAlbumProgram();
//        // 更新时长与状态为转码成功
//        program2.setId(program.getId());
//        program2.setStatus(VodStatus.WAIT_EDIT.getCode());
//        program2.setTime(duration.intValue());
//        //
//        // System.out.println("我更新状态完毕了");
//        // System.out.println("我已进入获取当前视频的转码后的信息");
//        if (program.getId() == null) {
//            log.error(fileId + "视频文件不存在");
//            return;
//        }
//        QcloudApiModuleCenter module = VodUtils.getConfig();
//        TreeMap<String, Object> params = VodUtils.getParam();
//        params.put("fileId", fileId);
//        params.put("infoFilter.0", "transcodeInfo");
//        String result = null;
//        result = module.call("GetVideoInfo", params);
//        JSONObject object = new JSONObject(result);
//        log.info(result);
//        if (object.getInt("code") == 0) {
//            JSONObject jarr = object.getJSONObject("transcodeInfo");
//            JSONArray arr = jarr.getJSONArray("transcodeList");
//            List<RadioAlbumProgram> list = new ArrayList<>();
//            for (int i = 0; i < arr.length(); i++) {
//                JSONObject jsonObj = arr.getJSONObject(i);
//                RadioAlbumProgram albumProgram = new RadioAlbumProgram();
//                // // 插入对象
//                albumProgram.setMp3downstreamaddress(jsonObj.getString("url"));
//                albumProgram.setFileid(jsonObj.getString("fileId"));
//                albumProgram.setTitle(jsonObj.getString("title"));
//                albumProgram.setFree(jsonObj.getInt("free"));
//                albumProgram.setProgramid(jsonObj.getInt("programId"));
//                albumProgram.setTime(jsonObj.getInt("duration"));
//                int size = jsonObj.getInt("size");
//                BigDecimal bg = new BigDecimal((float) size / 1024 / 1024).setScale(2, RoundingMode.UP);
//                albumProgram.setSize(bg.floatValue());
//                albumProgram.setOutputrateone(jsonObj.getInt("bitrate"));
//                String md5 = jsonObj.getString("md5");
//                albumProgram.setProgramid(program.getId());
//                list.add(program);
//            }
//            radioAlbumProgramMapper.deleteByVodId(program.getId());
//            radioAlbumProgramMapper.inserts(list);
//        } else {
//            log.error(object.toString());
//        }
//    }
}
